import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const service = axios.create({
  baseURL: '/exam-client', // api的base_url
  timeout: 30 * 1000 // 超时时间
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers['content-type'] = 'application/json; charset=utf-8'
    config.headers.dataType = 'json'
    let token = sessionStorage.getItem('token')

    if (config.url.indexOf('.json') > 0) {
      config.baseURL = '/'
    }
    
    if (token) {
      // 存在将token写入请求的header中
      // 请根据实际项目的 Authorization 字段自行修改
      config.headers.token = token
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// 响应拦截器，配置接口约定规则，统一处理错误业务
service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.request.responseURL.indexOf('.json') < 0) {
      if (res.code != 0) {
        // 此处为弹窗提示错误信息
        if (res.code === 401) {
          ElMessageBox.alert('登录已超时，请重新登录', '提示', {
            confirmButtonText: '确定',
            callback: () => {
              location.href = '/login'
            }
          })
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
            duration: 5 * 1000
          })
        }
      }
    } 
    return response
  },
  // http响应状态码处理
  error => {
    if (error.code === 'ECONNABORTED') {
      ElMessage({
        message: '网络异常，请稍后重试',
        type: 'error',
        duration: 3 * 1000
      })
    } else {
      switch (error.response.status) {
        case 401:
          ElMessageBox.alert('登录已超时，请重新登录', '提示', {
            confirmButtonText: '确定',
            callback: () => {
              sessionStorage.removeItem('token')
              location.href = '#/'
            }
          })
          break
        case 500:
          ElMessage({
            message: '服务器端异常，请稍后重试',
            type: 'error',
            duration: 3 * 1000
          })
          break
        default:
          ElMessage({
            message: '未知异常，请稍后重试',
            type: 'error',
            duration: 3 * 1000
          })
      }
    }
    return Promise.reject(error)
  }
)

export default service
